import { defineStore } from 'pinia'
import { sysMenu } from "../api/userManagement/index";
import { IMenuItem, INavItem, ITreeMenuItem } from '../interface/menu';
import { flatter, ifChildrenNull } from '../utils'

interface usersotre {
    test: any,
    dark: any,
    menuList: any,
    userRouters: any,
    navList: any,
    collapse: boolean,
    ids: any,
    routes: any,
    ButtonPermission: any,
}
export const useUserStore = defineStore('layout', {
    state: (): usersotre => {
        return {
            test: document.querySelector('html')!.className,
            dark: false,
            menuList: [],
            userRouters: [],
            routes: [],
            navList: [{ name: "首页", path: "/index/home" }] as INavItem[],
            collapse: false,
            ids: '',
            ButtonPermission:[]
        }
    },
    actions: {
        // async getMenuList() {
        //     const { getLocalStorage } = useLocalStorage();
        //     this.menuList = await userSysMenu(getLocalStorage('linkSystem'));
        // },
        // 获取用户树形结构菜单
        async setUserRouters(data: any) {

            data.forEach((item: any) => {
                item.children = item.children !== null ? item.children : []
            })
            this.menuList = data;

            this.userRouters = ifChildrenNull(data);

        },
        //关闭nav导航
        closeNav(index: number) {
            this.navList.splice(index, 1);
        },
        //新增nav导航 path-是每次点击切换的路径 /index/index
        setNavList(path: string) {
            let menuList: any[] = [];
            const navItem = {} as INavItem;
            this.userRouters.forEach((item: ITreeMenuItem) => {
                //菜单的子路由放到menuList数组里面
                menuList.push(item.children);
            });
            // 所有子路由的数据处理到一个数组里
            menuList = flatter(menuList);
            menuList.forEach((item: ITreeMenuItem) => {

                if (item && item.path == path) {
                    navItem.name = item.name;
                    navItem.path = item.path;
                }
            });
            const isBeing = this.navList.some((item: INavItem) => item.path == navItem.path);
            if (!isBeing && navItem && navItem.path) {
                this.navList.push(navItem)
            }
        },
        //关闭当前标签和首页标签之外的所有标签
        cloneOtherNav(currrentPath: string) {
            this.navList = [{ name: "首页", path: "/index/home" }];
            this.setNavList(currrentPath);
        },

        // 黑夜模式切换
        darkSwitch() {
            const html = document.querySelector('html')!;
            if (this.dark) {
                html.className = 'dark';

            } else {
                html.className = '';
            }
        }

    }
})

export default useUserStore;

